<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
	*{
		margin: 0;
		padding: 0;
	}
	.main{
		width: 500px;
		height: 500px;
		border: 1px solid black;
		margin: 0 auto;
		position: relative;
	}
	#div1 {
		width:100px;
		height:100px;
		background:#CCC;
		position:absolute;
		left: 0;
		top: 0;
	}
</style>
<script>
document.onkeydown=function (ev)
{
	var oEvent=ev||event;
	var oDiv=document.getElementById('div1');
	var mainDiv=document.getElementById('main');
	
	var maxWidth = mainDiv.clientWidth;
	var oWidth = oDiv.offsetWidth;
	console.log(oWidth);
	
	if(oEvent.keyCode==37)
	{
		if (oDiv.offsetLeft - 10 <= 0) {
			oDiv.style.left= 0;
		} else{
			oDiv.style.left=oDiv.offsetLeft-10+'px';
		}
		
	}
	else if(oEvent.keyCode==39)
	{
		if (oDiv.offsetLeft + oWidth + 10 > maxWidth) {
			console.log(maxWidth - oWidth);
			oDiv.style.left= maxWidth - oWidth;
		} else{
			oDiv.style.left=oDiv.offsetLeft+10+'px';
		}
	}
};
</script>
</head>

<body>
	<div class="main" id="main">
		<div id="div1"></div>
	</div>
</body>
</html>
